package com.ruoyi.common.utils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.imageFIle.entity.ImageFile;
import com.ruoyi.common.imageFIle.service.ImageFIleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * 用于远程上传图片工具类
 *
 *  @auther zcy
 *  @data 2023/3/17 14:10
 */
@Configuration
public class UploadFileUtils {

    private static String url;

    private static String avatarUrl;

    private static String delUrl;

    private static String projectName;

    @Resource
    ImageFIleService imageFIleService;

    private static ImageFIleService ffileManageService;

    @PostConstruct
    public void init(){
        ffileManageService = imageFIleService; //进行赋值,实际上调用的是imageFIleService
    }
    @Value("${imageServer.url}")
    public void setToUrl(String url) {
        this.url = url;
    }
    @Value("${imageServer.avatarUrl}")
    public void setToAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }
    @Value("${imageServer.projectName}")
    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }
    @Value("${imageServer.delUrl}")
    public void setDelUrl(String delUrl) {
        this.delUrl = delUrl;
    }


    /**
     * 批量上传
     * @param files
     * @return
     */
    public static String uploadListFile(MultipartFile [] files) {
        // 用户拼接id
        StringBuilder  ids = new StringBuilder();
        // 循环上传图片到服务器
        if(files!=null&&files.length>0){
            for (int i=0;i< files.length;i++) {
                String id = uploadFile(files[i]);
                if(i==files.length-1){
                    ids.append(id);
                }else {
                    ids.append(id).append(",");
                }
            }
        }else{
            ids.append(0);
        }
        return ids.toString();
    }
    /**
     * 新增图片
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file) {
        String toUrl = url +"/"+ projectName;
        // 判断对象是否为空
        if(file.isEmpty()&&file.getSize()==0){
            return "";
        }
        // 获取字节
        byte[] fileByte = null;
        try {
            fileByte = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        DataOutputStream dos = null;
        InputStream is = null;
        InputStreamReader isr = null;
        String end = "\r\n";
        String twoHyphens = "--";
        // 分隔符
        String boundary = "---------------------------823928434";
        try {
            //创建url连接
            URL url = new URL(toUrl);
            // 创建HttpURLConnection 连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置输入
            httpURLConnection.setDoInput(true);
            // 设置输出
            httpURLConnection.setDoOutput(true);
            // 不使用缓存
            httpURLConnection.setUseCaches(false);
            //连接超时 单位毫秒
            httpURLConnection.setConnectTimeout(10000);
            //读取超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);
            // 设置请求方式
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符集
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置Content-Type
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename="+file.getOriginalFilename() + end);
            dos.writeBytes(end);
            dos.write(fileByte);
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();
            // 读取服务器返回结果
            is = httpURLConnection.getInputStream();
            isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();
            JSONObject jsonObject =  JSON.parseObject(result);
            Boolean flag = jsonObject.getBoolean("flag");
            // 判断是否上传成共
            if(flag){
                //返回的id值
                String data = jsonObject.getString("data");
                //创建对象
                ImageFile imageFile=new ImageFile();

                imageFile.setImageName(data);
                //类型
                String fileName = file.getOriginalFilename();
                //获取文件的后缀名
                String[] fileNameWords = fileName.split("\\.");
                //加上.
                String fileType = "." + fileNameWords[fileNameWords.length - 1];
                imageFile.setFileType(fileType);
                //大小
                imageFile.setFileSize(String.valueOf(file.getSize()));
                //uuidName
                String uuid = UUID.randomUUID().toString();
                imageFile.setFileUuidName(uuid+fileType);
                //创建时间
                imageFile.setCreateTime(new Date());
                //创建对象
                boolean b = ffileManageService.addFile(imageFile);
                if(!b){
                    return "";
                }
                return jsonObject.getString("data");
            }else{
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭读字符流
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            // 关闭字节输入流
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            // 关闭数据输出流
            if(dos!=null){
                try {
                    dos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return "";
    }

    /**
     * 新增头像图片
     * @param file
     * @return
     */
    public static String uploadAvatar(MultipartFile file) {
        String toUrl = avatarUrl +"/"+ projectName;
        // 判断对象是否为空
        if(file.isEmpty()&&file.getSize()==0){
            return "";
        }
        // 获取字节
        byte[] fileByte = null;
        try {
            fileByte = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        DataOutputStream dos = null;
        InputStream is = null;
        InputStreamReader isr = null;
        String end = "\r\n";
        String twoHyphens = "--";
        // 分隔符
//        String boundary = "---------------------------823928434";
        String boundary = "---------------------------" + System.currentTimeMillis();
        try {
            //创建url连接
            URL url = new URL(toUrl);
            // 创建HttpURLConnection 连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置输入
            httpURLConnection.setDoInput(true);
            // 设置输出
            httpURLConnection.setDoOutput(true);
            // 不使用缓存
            httpURLConnection.setUseCaches(false);
            //连接超时 单位毫秒
            httpURLConnection.setConnectTimeout(10000);
            //读取超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);
            // 设置请求方式
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符集
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置Content-Type
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//            httpURLConnection.setRequestProperty("Content-Type", file.getContentType());
//            httpURLConnection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getOriginalFilename() + "\"");
            dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"avatarfile\"; filename=\"" + file.getOriginalFilename() + "\"" + end);
            dos.writeBytes("Content-Type: " + file.getContentType() + end);
            dos.writeBytes(end);
            dos.write(fileByte);
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();
            // 读取服务器返回结果
            is = httpURLConnection.getInputStream();
            isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();
            JSONObject jsonObject =  JSON.parseObject(result);
            Boolean flag = jsonObject.getBoolean("flag");
            // 判断是否上传成共
            if(flag){
                return jsonObject.getString("data");
            }else{
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭读字符流
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            // 关闭字节输入流
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            // 关闭数据输出流
            if(dos!=null){
                try {
                    dos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return "";
    }


    /**
     * 删除图片及信息
     * @param id
     * @return
     */
    public static boolean deleteFileById(Integer id) {
        if(id!=0&&isNotEmpty(delUrl)){
            URL url = null;
            try {
                // 拼接id
                url = new URL(delUrl+"?id="+id);
            } catch (MalformedURLException exception) {
                exception.printStackTrace();
            }
            InputStream is = null;
            InputStreamReader isr = null;
            HttpURLConnection httpURLConnection = null;
            try {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                // 是遏制请求格式
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                // 设置请求方式
                httpURLConnection.setRequestMethod("DELETE");
                is = httpURLConnection.getInputStream();
                isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String result = br.readLine();
                JSONObject jsonObject =  JSON.parseObject(result);
                Boolean flag = jsonObject.getBoolean("flag");
                return flag;
            } catch (IOException exception) {
                exception.printStackTrace();
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                // 关闭读字符流
                if(isr!=null){
                    try {
                        isr.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                // 关闭字节输入流
                if(is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return false;
    }

    /**
     * 判断字符串是个否为空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return str != null && !"".equals(str);
    }
}

